package com.giisoo.webshell.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.fileupload.FileItem;
import org.giiwa.core.base.IOUtil;
import org.giiwa.core.base.Shell;
import org.giiwa.core.bean.X;
import org.giiwa.core.json.JSON;
import org.giiwa.framework.web.Model;
import org.giiwa.framework.web.Path;

public class shell extends Model {

  @Path(login = true, access = "access.config.admin")
  public void onGet() {
    this.show("/shell/shell.html");
  }

  @Path(path = "download/(.*)", login = true, access = "access.config.admin")
  public void download(String filename) {
    filename = filename.trim();
    File f = new File(filename);

    if (f.exists()) {
      this.setContentType("application/octet-stream");
      this.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

      try {
        OutputStream out = this.getOutputStream();
        InputStream in = new FileInputStream(f);

        IOUtil.copy(in, out, true);
      } catch (Exception e) {
        log.error(filename, e);
      }
    }
  }

  @Path(path = "upload", login = true, access = "access.config.admin")
  public void upload() {
    JSON jo = new JSON();

    FileItem file = this.getFile("file");
    if (file != null) {
      String filename = file.getName();
      try {
        File f = new File(filename);
        if (!f.exists()) {
          OutputStream out = new FileOutputStream(filename);
          InputStream in = file.getInputStream();

          IOUtil.copy(in, out, true);

          jo.put(X.MESSAGE, f.getCanonicalPath());
        } else {
          jo.put(X.ERROR, "file exists, can not override! " + f.getCanonicalPath());
        }
      } catch (Exception e) {
        log.error(filename, e);

        jo.put(X.ERROR, e.getMessage());
      }

    } else {
      jo.put(X.ERROR, "file missed");
    }

    this.response(jo);
  }

  @Path(path = "run", login = true, access = "access.config.admin")
  public void run() {
    JSON jo = new JSON();

    String line = this.getString("line");
    if (!X.isEmpty(line)) {
      try {
        String r = Shell.run(line);
        r = r.replaceAll("\n", "<br/>").replaceAll(" ", "&nbsp;").replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
        jo.put(X.MESSAGE, r);
        jo.put(X.STATUS, 200);
        log.warn(line);

      } catch (Exception e) {
        log.error(line, e);
        String r = e.getMessage();
        r = r.replaceAll("\n", "<br/>");
        jo.put(X.MESSAGE, r);
        jo.put(X.STATUS, 201);
      }
    } else {
      jo.put(X.STATUS, 200);
    }
    this.response(jo);
  }

}
